package cn.edu.sgu.www.pms.shiro;

import cn.edu.sgu.www.pms.entity.User;
import cn.edu.sgu.www.pms.enums.LockStatus;
import cn.edu.sgu.www.pms.util.PasswordEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

/**
 * 密码匹配器
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Component
public class UserPasswordMatcher implements CredentialsMatcher {

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        PrincipalCollection principals = authenticationInfo.getPrincipals();
        User user = (User) principals.getPrimaryPrincipal();

        // 账号被锁定，禁止登录
        if (LockStatus.isLocked(user.getLockStatus())) {
            throw new AuthenticationException("账号已被锁定，禁止登录~");
        }

        // 得到用户输入的密码
        String password = new String(token.getPassword());
        // 得到数据库中的密码（正确的密码）
        String encodedPassword = user.getPassword();

        // 匹配密码
        if (!PasswordEncoder.matches(password, encodedPassword)) {
            throw new AuthenticationException("登录失败，用户名或密码不正确！");
        }

        return true;
    }

}